#include "thread.h"
#include "index.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonParseError>
#include <QString>
#include <QDebug>
#include <QFile>
#include <QHostAddress>
Sthread::Sthread(qintptr sock, QObject *parent) : QThread{parent}
{
    //socket1 = new QTcpSocket(this);
    // socket1->setSocketDescriptor(sock1);
    // socket1 = tcp;
    //socket1->setSocketDescriptor(sock);
    // sock1=sock;
    //  qDebug()<<"Sthread sock1:"<<(socket1->readAll());

    socket1 = new QTcpSocket(this);
    tcpSktList.append(socket1);//添加到QTcpSocket*的列表，方便管理
    socket1->setSocketDescriptor(sock);
    connect(socket1, &QTcpSocket::readyRead, this, &Sthread::onReadyRead); //有可读的信息，触发读槽函数
    connect(socket1, &QTcpSocket::disconnected, this, &Sthread::onDisconnected);
    qDebug() << "connect" << socket1->peerAddress().toString() << ":" << socket1->peerPort();

}

void Sthread::run()
{
    // socket1 = new QTcpSocket(this);
    // socket1->setSocketDescriptor(sock1);
    //取出建立好连接的套接字
    //QTcpSocket *socket1 = server->nextPendingConnection();

    //获取对方的IP和端口
    QHostAddress clientIp = socket1->peerAddress();//客户端的IP
    qint16 port = socket1->peerPort();//客户端的端口

    //QByteArray array = socket1->readAll();
    qDebug()<<"Sthread sock1:"<<(socket1->readAll());

    if(tcpSktList.contains(socket1))
    {
        qDebug()<<QString("%1:%2的连接早已建立过").arg(clientIp.toString()).arg(port);
    }
    else
    {
        qDebug()<<QString("新的连接已建立 %1:%2").arg(clientIp.toString()).arg(port);
        tcpSktList.append(socket1);//记录下客户端发起的连接
        connect(socket1, SIGNAL(disconnected()), this, SLOT(onDisconnected()));//客户端掉线处理
        connect(socket1, SIGNAL(readyRead()), this, SLOT(onReadyRead()));//客户端发来的数据处理
        //connect(socket1, SIGNAL(readyRead()), this, SLOT(sec()));//客户端发来的数据处理
    }
    // socket1->close();
    // socket1->deleteLater();
    // exec();
}

void Sthread::onReadyRead()
{
    QTcpSocket* socket1 = static_cast<QTcpSocket*>(sender());
    QJsonObject json;
    if(socket1)
    {
        //从通信套接字中取出内容
        QByteArray array = socket1->readAll();
        qDebug()<<(socket1->readAll());
        QString request = QString::fromUtf8(array);
        qDebug() << "正在从浏览器读取数据= " << request;//打印收到的来自客户端的消息
        qDebug() << "sec " << request.indexOf("/sec");
        // QString ct = request.startsWith("GET")
        if(request.startsWith("GET"))//如果是GET请求
        {
            // QFile file("/Users/Administrator/Documents/http_demo/index.txt");

            if(request.indexOf("/sec")>0){
                QSqlQuery query("SELECT * FROM dbo.dianpu;");
                //qDebug()<<"ID     LoginName        LoginTime                LogoutTime        OPeration";
                QJsonArray root;
                QJsonObject json;
                int i=0;
                while (query.next())
                {
                    json.insert("time",query.value(2).toString());
                    json.insert("name",query.value(0).toString());
                    json.insert("sale",query.value(1).toString());
                    json.insert("mark",query.value(3).toString());
                    root.append(json);
                    i++;
                    //qDebug()<<root;

                }

                QJsonDocument doc(root);
                QString jsonString = doc.toJson();
                qDebug()<<"jsonstring:"<<jsonString;
                char *ch = jsonString.toUtf8().data();
                //QByteArray utf8Data = jsonString.toLocal8Bit().data();
                socket1->write("HTTP/1.1 200 OK\r\n");
                socket1->write("Content-Type: text/html\r\n");
                socket1->write("\r\n");
                socket1->write(ch);
                socket1->flush();
                if(!socket1->waitForBytesWritten(3000)){
                    socket1->close();
                }
            }else  if(request.indexOf("/caixid")>0){
                QSqlQuery query("SELECT * FROM dbo.caidan;");
                //qDebug()<<"ID     LoginName        LoginTime                LogoutTime        OPeration";
                QJsonArray root;
                QJsonObject json;
                int i=0;
                while (query.next())
                {
                    json.insert("ID",query.value(0).toString());
                    json.insert("cuisine",query.value(1).toString());
                    json.insert("name",query.value(2).toString());
                    root.append(json);
                    i++;
                    //qDebug()<<root;

                }

                QJsonDocument doc(root);
                QString jsonString = doc.toJson();
                qDebug()<<"jsonstring:"<<jsonString;
                char *ch = jsonString.toUtf8().data();
                //QByteArray utf8Data = jsonString.toLocal8Bit().data();
                socket1->write("HTTP/1.1 200 OK\r\n");
                socket1->write("Content-Type: text/html\r\n");
                socket1->write("\r\n");
                socket1->write(ch);
                socket1->flush();
                if(!socket1->waitForBytesWritten(3000)){
                    socket1->close();
                }
            }else if(request.indexOf("/orderd")>0){
                QSqlQuery query("SELECT * FROM dbo.dingdan;");
                //qDebug()<<"ID     LoginName        LoginTime                LogoutTime        OPeration";
                QJsonArray root;
                QJsonObject json;
                int i=0;
                while (query.next())
                {
                    json.insert("phone",query.value(0).toString());
                    json.insert("ID",query.value(1).toString());
                    json.insert("orderid",query.value(2).toString());
                    json.insert("money",query.value(3).toString());
                    json.insert("way",query.value(4).toString());
                    json.insert("name",query.value(5).toString());
                    json.insert("addre",query.value(6).toString());
                    root.append(json);
                    i++;
                    //qDebug()<<root;

                }

                QJsonDocument doc(root);
                QString jsonString = doc.toJson();
                qDebug()<<"jsonstring:"<<jsonString;
                char *ch = jsonString.toUtf8().data();
                //QByteArray utf8Data = jsonString.toLocal8Bit().data();
                socket1->write("HTTP/1.1 200 OK\r\n");
                socket1->write("Content-Type: text/html\r\n");
                socket1->write("\r\n");
                socket1->write(ch);
                socket1->flush();
                if(!socket1->waitForBytesWritten(3000)){
                    socket1->close();
                }
            }else if(request.indexOf("/songhuod")>0){
                QSqlQuery query("SELECT * FROM dbo.sonhuoyuan;");
                //qDebug()<<"ID     LoginName        LoginTime                LogoutTime        OPeration";
                QJsonArray root;
                QJsonObject json;
                int i=0;
                while (query.next())
                {
                    json.insert("ID",query.value(0).toString());
                    json.insert("name",query.value(1).toString());
                    json.insert("phone",query.value(2).toString());
                    json.insert("shopname",query.value(3).toString());
                    root.append(json);
                    i++;
                    //qDebug()<<root;

                }

                QJsonDocument doc(root);
                QString jsonString = doc.toJson();
                qDebug()<<"jsonstring:"<<jsonString;
                char *ch = jsonString.toUtf8().data();
                //QByteArray utf8Data = jsonString.toLocal8Bit().data();
                socket1->write("HTTP/1.1 200 OK\r\n");
                socket1->write("Content-Type: text/html\r\n");
                socket1->write("\r\n");
                socket1->write(ch);
                socket1->flush();
                if(!socket1->waitForBytesWritten(3000)){
                    socket1->close();
                }
            }else if(request.indexOf("/wuliud")>0){
                QSqlQuery query("SELECT * FROM dbo.wuliu;");
                //qDebug()<<"ID     LoginName        LoginTime                LogoutTime        OPeration";
                QJsonArray root;
                QJsonObject json;
                int i=0;
                while (query.next())
                {
                    json.insert("ID",query.value(1).toString());
                    json.insert("home",query.value(0).toString());
                    json.insert("time",query.value(2).toString());
                    root.append(json);
                    i++;
                    //qDebug()<<root;

                }

                QJsonDocument doc(root);
                QString jsonString = doc.toJson();
                qDebug()<<"jsonstring:"<<jsonString;
                char *ch = jsonString.toUtf8().data();
                //QByteArray utf8Data = jsonString.toLocal8Bit().data();
                socket1->write("HTTP/1.1 200 OK\r\n");
                socket1->write("Content-Type: text/html\r\n");
                socket1->write("\r\n");
                socket1->write(ch);
                socket1->flush();
                if(!socket1->waitForBytesWritten(3000)){
                    socket1->close();
                }
            }else if(request.indexOf("/kefud")>0){
                QSqlQuery query("SELECT * FROM dbo.kefu;");
                //qDebug()<<"ID     LoginName        LoginTime                LogoutTime        OPeration";
                QJsonArray root;
                QJsonObject json;
                int i=0;
                while (query.next())
                {
                    json.insert("ID",query.value(0).toString());
                    json.insert("name",query.value(1).toString());
                    json.insert("shopname",query.value(2).toString());
                    root.append(json);
                    i++;
                    //qDebug()<<root;

                }

                QJsonDocument doc(root);
                QString jsonString = doc.toJson();
                qDebug()<<"jsonstring:"<<jsonString;
                char *ch = jsonString.toUtf8().data();
                //QByteArray utf8Data = jsonString.toLocal8Bit().data();
                socket1->write("HTTP/1.1 200 OK\r\n");
                socket1->write("Content-Type: text/html\r\n");
                socket1->write("\r\n");
                socket1->write(ch);
                socket1->flush();
                if(!socket1->waitForBytesWritten(3000)){
                    socket1->close();
                }
            }else  if(request.indexOf("/log")>0)
            {
                QFile file("O:/QT File/database/uiui/login.html");
                if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                {
                    qDebug() << "文件打开失败";
                    return;
                }
                QString tempStr = "";//临时字符串

                while (!file.atEnd())//判断是否读到文件末尾，如果已经达到末尾，返回 true，否则返回 false。
                {
                    //tempStr = file.readLine();  //读取文件中一行
                    tempStr = file.readAll();   //读取文件中所有内容
                    // qDebug() <<"tempStr = "<<tempStr;
                    qDebug() <<"tempStr = success ";
                }
                //sec();
                //char *ch = tempStr.toLatin1().data();
                char *ch = tempStr.toLocal8Bit().data();
                socket1->write("HTTP/1.1 200 OK\r\n");
                socket1->write("Content-Type: text/html\r\n");
                socket1->write("\r\n");
                socket1->write(ch);
                socket1->flush();

                if(!socket1->waitForBytesWritten(3000)){
                    socket1->close();
                }
                qDebug() << "login文件发送成功";
            }else if(request.indexOf("/select")>0)
            {
                QFile file("O:/QT File/database/uiui/select.html");
                if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                {
                    qDebug() << "文件打开失败";
                    return;
                }
                QString tempStr = "";//临时字符串

                while (!file.atEnd())//判断是否读到文件末尾，如果已经达到末尾，返回 true，否则返回 false。
                {
                    //tempStr = file.readLine();  //读取文件中一行
                    tempStr = file.readAll();   //读取文件中所有内容
                     qDebug() <<"tempStr = "<<tempStr;
                    //qDebug() <<"tempStr = success ";
                }
                //sec();
                //char *ch = tempStr.toLatin1().data();
                char *ch = tempStr.toLocal8Bit().data();
                socket1->write("HTTP/1.1 200 OK\r\n");
                socket1->write("Content-Type: text/html\r\n");
                socket1->write("\r\n");
                socket1->write(ch);
                socket1->flush();
                qDebug() << "select.html文件发送成功";
                if(!socket1->waitForBytesWritten(3000)){
                    socket1->close();
                }

            }else if(request.indexOf("/kefu")>0)
            {
                QFile file("O:/QT File/database/uiui/kefu.html");
                if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                {
                    qDebug() << "文件打开失败";
                    return;
                }
                QString tempStr = "";//临时字符串

                while (!file.atEnd())//判断是否读到文件末尾，如果已经达到末尾，返回 true，否则返回 false。
                {
                    //tempStr = file.readLine();  //读取文件中一行
                    tempStr = file.readAll();   //读取文件中所有内容
                    // qDebug() <<"tempStr = "<<tempStr;
                    qDebug() <<"tempStr = success ";
                }
                //sec();
                //char *ch = tempStr.toLatin1().data();
                char *ch = tempStr.toLocal8Bit().data();
                socket1->write("HTTP/1.1 200 OK\r\n");
                socket1->write("Content-Type: text/html\r\n");
                socket1->write("\r\n");
                socket1->write(ch);
                socket1->flush();

                if(!socket1->waitForBytesWritten(3000)){
                    socket1->close();
                }
                qDebug() << "kefu文件发送成功";
            }else if(request.indexOf("/order")>0)
            {
                QFile file("O:/QT File/database/uiui/order.html");
                if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                {
                    qDebug() << "文件打开失败";
                    return;
                }
                QString tempStr = "";//临时字符串

                while (!file.atEnd())//判断是否读到文件末尾，如果已经达到末尾，返回 true，否则返回 false。
                {
                    //tempStr = file.readLine();  //读取文件中一行
                    tempStr = file.readAll();   //读取文件中所有内容
                    // qDebug() <<"tempStr = "<<tempStr;
                    qDebug() <<"tempStr = success ";
                }
                //sec();
                //char *ch = tempStr.toLatin1().data();
                char *ch = tempStr.toLocal8Bit().data();
                socket1->write("HTTP/1.1 200 OK\r\n");
                socket1->write("Content-Type: text/html\r\n");
                socket1->write("\r\n");
                socket1->write(ch);
                socket1->flush();

                if(!socket1->waitForBytesWritten(3000)){
                    socket1->close();
                }
                qDebug() << "订单文件发送成功";
            }else if(request.indexOf("/wuliu")>0)
            {
                QFile file("O:/QT File/database/uiui/wuliu.html");
                if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                {
                    qDebug() << "文件打开失败";
                    return;
                }
                QString tempStr = "";//临时字符串

                while (!file.atEnd())//判断是否读到文件末尾，如果已经达到末尾，返回 true，否则返回 false。
                {
                    //tempStr = file.readLine();  //读取文件中一行
                    tempStr = file.readAll();   //读取文件中所有内容
                    // qDebug() <<"tempStr = "<<tempStr;
                    qDebug() <<"tempStr = success ";
                }
                //sec();
                //char *ch = tempStr.toLatin1().data();
                char *ch = tempStr.toLocal8Bit().data();
                socket1->write("HTTP/1.1 200 OK\r\n");
                socket1->write("Content-Type: text/html\r\n");
                socket1->write("\r\n");
                socket1->write(ch);
                socket1->flush();

                if(!socket1->waitForBytesWritten(3000)){
                    socket1->close();
                }
                qDebug() << "物流文件发送成功";
            }else if(request.indexOf("/caixi")>0)
            {
                QFile file("O:/QT File/database/uiui/caixi.html");
                if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                {
                    qDebug() << "文件打开失败";
                    return;
                }
                QString tempStr = "";//临时字符串

                while (!file.atEnd())//判断是否读到文件末尾，如果已经达到末尾，返回 true，否则返回 false。
                {
                    //tempStr = file.readLine();  //读取文件中一行
                    tempStr = file.readAll();   //读取文件中所有内容
                    // qDebug() <<"tempStr = "<<tempStr;
                    qDebug() <<"tempStr = success ";
                }
                //sec();
                //char *ch = tempStr.toLatin1().data();
                char *ch = tempStr.toLocal8Bit().data();
                socket1->write("HTTP/1.1 200 OK\r\n");
                socket1->write("Content-Type: text/html\r\n");
                socket1->write("\r\n");
                socket1->write(ch);
                socket1->flush();

                if(!socket1->waitForBytesWritten(3000)){
                    socket1->close();
                }
                qDebug() << "物流文件发送成功";
            }else if(request.indexOf("/songhuo")>0)
            {
                QFile file("O:/QT File/database/uiui/songhuo.html");
                if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                {
                    qDebug() << "文件打开失败";
                    return;
                }
                QString tempStr = "";//临时字符串

                while (!file.atEnd())//判断是否读到文件末尾，如果已经达到末尾，返回 true，否则返回 false。
                {
                    //tempStr = file.readLine();  //读取文件中一行
                    tempStr = file.readAll();   //读取文件中所有内容
                    // qDebug() <<"tempStr = "<<tempStr;
                    qDebug() <<"tempStr = success ";
                }
                //sec();
                //char *ch = tempStr.toLatin1().data();
                char *ch = tempStr.toLocal8Bit().data();
                socket1->write("HTTP/1.1 200 OK\r\n");
                socket1->write("Content-Type: text/html\r\n");
                socket1->write("\r\n");
                socket1->write(ch);
                socket1->flush();

                if(!socket1->waitForBytesWritten(3000)){
                    socket1->close();
                }
                qDebug() << "送货文件发送成功";
            }


            if(request.indexOf("/favicon.ico")>0)
            {
                socket1->write("HTTP/1.1 200 OK\r\n");
                socket1->write("Content-Type: text/html\r\n");
                socket1->write("\r\n");
                socket1->write("404");
                socket1->flush();
                qDebug() << "404发送成功";
                if(!socket1->waitForBytesWritten(3000)){
                    socket1->close();
                }
            }
        }
        // }
        //  if(socket1)
        //  {
        //      //从通信套接字中取出内容
        //      QByteArray array = socket1->readAll();
        //      qDebug()<<(socket1->readAll());
        //      QString request = QString::fromUtf8(array);
        //      qDebug() << "正在从浏览器读取数据= " << request;//打印收到的
        if(request.startsWith("POST"))//如果是POST请求
        {
            qDebug() << "POST!!!!!!!!!!!";
            QString a,b;
            QString temp1;
            int n = request.lastIndexOf("\\");
            temp1 = request.mid(n+1);
            //QString temp[n+1];
            int i=0;
            // for(int y=0;y<n+1;y++)
            // {
            //     temp[y] = temp1[y];
            // }
            int n1 = temp1.lastIndexOf("=");
            int n2 = temp1. indexOf("account=");
            int n3 = temp1. indexOf("&");
            int n4 =n3-n2;
            qDebug() << "n2："<<n2;
            qDebug() << "n3："<<n3;
            qDebug() << "n4："<<n4;
            QString temp2 = temp1.mid(n1+1);
            QString temp3 = temp1.sliced(n2+8,n4-8);
            qDebug() << "temp2密码："<<temp2;
            qDebug() << "temp3账号："<<temp3;
            if(temp2=="112334"&&temp3=="45")
            {
                qDebug() << "登录成功";
                // QFile file("/Users/Administrator/Documents/http_demo/index.txt");
                QFile file("O:/QT File/database/uiui/select.html");
                if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
                {
                    qDebug()<< "select文件打开失败";
                    return;
                }
                QString tempStr = "";//临时字符串
                while (!file.atEnd())//判断是否读到文件末尾，如果已经达到末尾，返回 true，否则返回 false。
                {
                    //tempStr = file.readLine();  //读取文件中一行
                    tempStr = file.readAll();   //读取文件中所有内容
                    qDebug() <<"tempStr = "<<tempStr;
                }
                json.insert("id","success");
                QJsonDocument doc(json);
                QString jsonString = doc.toJson();
                char *ch = jsonString.toLocal8Bit().data();
                //sec();
                //char *ch = tempStr.toLatin1().data();
                // char *ch = tempStr.toLocal8Bit().data();
                socket1->write("HTTP/1.1 200 OK\r\n");
                socket1->write("Content-Type: text/html\r\n");
                socket1->write("\r\n");
                socket1->write(ch);
                socket1->flush();
                qDebug() << "发送完毕！";
            }
        }
    }

    socket1->close();
    socket1->deleteLater();
    exec();
}

void Sthread::onDisconnected()
{
    QTcpSocket* socket1 = static_cast<QTcpSocket*>(sender());
    //获取对方的IP和端口
    QHostAddress clientIp = socket1->peerAddress();//客户端的IP
    qint16 port = socket1->peerPort();//客户端的端口
    qDebug()<<QString("客户端掉线 %1:%2").arg(clientIp.toString()).arg(port);

    tcpSktList.removeOne(socket1);

}
